#include "protobuf/codec/codec.h"
#include "protobuf/codec/dispatcher.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"
#include "muduo/net/TcpClient.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/net/EventLoopThread.h"

#include "protobuf/codec/codec.cc"

#include "request.pb.h"
#include <iostream>
#include <functional>
#include <string>


class Client{
public:
typedef std::shared_ptr<google::protobuf::Message> MessagePtr; 
typedef std::shared_ptr<request::AddResponse> AddResponsePtr;
typedef std::shared_ptr<request::TranslateResponse> TranslateResponsePtr;

//使用 _loopthread.startLoop() 获取loop，因为在客户端不能发生阻塞没导致无法send
    Client(std::string sip,int16_t sport):
    _client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"TcpClient"),
    _dispatcher(std::bind(&Client::onknowMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3)),
    _codec(std::bind(&ProtobufDispatcher::onProtobufMessage,&_dispatcher,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3)),
    _latch(1)
    {
        //注册消息处理函数
        _dispatcher.registerMessageCallback<request::TranslateResponse>(std::bind(&Client::onTranslate,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
      //2. .... 
      _dispatcher.registerMessageCallback<request::AddResponse>(std::bind(&Client::onAdd,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));

      //再给server 注册处理函数 ； 连接事件就绪 / 正常事件就绪

      //连接就绪：
      _client.setConnectionCallback(std::bind(&Client::onConnection,this,std::placeholders::_1));

      //事件就绪：
      //对于绑定ProtobufCodec里面的onMessage函数，是因为需要进行数据的序列化操作，所以使用Protobuf
      _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage,&_codec,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }

    void connect()
    {
        _client.connect();//建立连接
        _latch.wait();//等待连接
    }



    void Translate(const std::string& message)
    {
        request::TranslateRequest resp;
        resp.set_msg(message);
        send(&resp);
    }

    void Add(int num1,int num2){
        request::AddRequest resp;
        resp.set_num1(num1);
        resp.set_num2(num2);

        send(&resp);
    }

private:

    bool send(const google::protobuf::Message* msg)
    {
        if(_conn->connected())
        {
            _codec.send(_conn,*msg);
            return true;
        }
        return false;
    }


  void onConnection(const muduo::net::TcpConnectionPtr &conn){
        if(!conn->connected())
        {
            std::cout << "新连接关闭" << std::endl;
        }
        else
        {
            std::cout << "新连接成功" << std::endl;
            _latch.countDown();//当连接成功后，唤醒 
            _conn = conn;//注意别忘了！
        }   
    }   


    void onTranslate(const muduo::net::TcpConnectionPtr&,
                                const TranslateResponsePtr& message,
                                muduo::Timestamp)
    {
        std::cout << "翻译结果" << message->msg() << std::endl;
    }

    void onAdd(const muduo::net::TcpConnectionPtr&,
                                const AddResponsePtr& message,
                                muduo::Timestamp){
        std::cout << "加法结果" << message->result() << std::endl;
    }

    void onknowMessage(const muduo::net::TcpConnectionPtr& conn,
                                const MessagePtr& message,
                                muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

private:
    ProtobufDispatcher _dispatcher;
    ProtobufCodec _codec;
    muduo::net::EventLoopThread _loopthread;//不在像中服务器使用eventloop，因为他是阻塞式的循环，这样会导致无法send
    muduo::net::TcpClient _client;

    muduo::CountDownLatch _latch;//进行防止等待连接导致的阻塞
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    Client client("127.0.0.1",8080);
    client.connect();

    client.Translate("apple");
    client.Add(1,2);

    sleep(1);

    return 0;
}
